package com.xueke.crawler.service.download;

import com.xueke.crawler.helper.ProxyHelper;
import com.xueke.crawler.model.DocRelation;
import com.xueke.crawler.model.User;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by weibo on 2017/5/13.
 *
 * @author weibo.qin
 * @version 2017/5/13
 */
@Component("normalUserDownloader")
public class NormalUserDownloader extends BaseDownloader {

    @Override
    public void download(int start, int end, int level, String userType) {

        int pageSize = 5;
        Map<String,String> cookies = new HashMap<String,String>();

        for (int i = 0; ; i++) {
            List<DocRelation> list = docRelationMapper.query2DownloadDocRelation(start, end, level, i * pageSize, pageSize);

            if (list.isEmpty()) {
                System.out.println("题目已经下载完毕！");
                return;
            }

            User user = userMapper.queryUser(i, userType);
            System.out.println(user.getName() + "--------" + user.getPassword());
            for (DocRelation docRelation : list) {

                 try {
                    String downloadUrl = ProxyHelper.parseDownloadUrl(null,String.valueOf(docRelation.getDocId()), user
                            .getName(),
                        user.getPassword(), 0,cookies);

                     if ("-9999".equalsIgnoreCase(downloadUrl)) {
                         // 更新账户作废.
                         userMapper.updateUserStatus(user.getName());
                         break;
                     }

                     if ("-9998".equalsIgnoreCase(downloadUrl)) {
                         // 题目作废.
                         docRelationMapper.updateInvalidDoc(String.valueOf(docRelation.getDocId()));
                         break;
                     }

                    doDownload(downloadUrl, docRelation.getDocId(),cookies);
                } catch (Exception e) {
                    e.printStackTrace();

                }

            }


        }


    }
}
